package 常用类.Arrays类;

import java.util.Arrays;
import java.util.Comparator;

/*
    自定义Book类，里面包含name和price，按照price排序从大到小，要求使用两种排序方式，有一个Book[] books = 4对象
    使用前面学过的传递实现Comparator接口匿名内存类，也称为定制排序
        1.从大到小
        2.从小到大
        3.按照书名从到小
 */
public class 练习题 {
    public static void main(String[] args) {
        Book[] books = new Book[4];
        books[0] = new Book("红楼梦", 100);
        books[1] = new Book("西游记", 120);
        books[2] = new Book("三国演义", 110);
        books[3] = new Book("水浒传", 99);
//        sortBook(books, new Comparator() {
//            @Override
//            public int compare(Object o1, Object o2) {
//                int book1 = (Integer)o1;
//                int book2 = (Integer) o2;
//                return book2 - book1;
//            }
//        });

//        Arrays.sort(books, new Comparator<Book>() {
//            @Override
//            public int compare(Book o1, Book o2) {
//                return o1.getPrice() - o2.getPrice();
//            }
//        });
//        System.out.println(Arrays.toString(books));

        Arrays.sort(books, new Comparator<Object>() {
            @Override
            public int compare(Object o1, Object o2) {
                Book book = (Book)o1;
                Book book2 = (Book)o2;
                int price = book.getPrice() - book2.getPrice();
                if(price < 0){
                    return -1;
                }else if(price > 0){
                    return 1;
                }else {
                    return 0;
                }

            }
        });
        for (Book book : books) {
            System.out.println(book);
        }
        System.out.println(Arrays.toString(books));
    }

    public static void sortBook(Book[] books, Comparator c){
        Book temp;
        for (int i = 0; i < books.length - 1; i++) {
            for (int j = 0; j < books.length - 1 -i; j++) {
                if(c.compare(books[j], books[j + 1]) < 0){
                    temp = books[j];
                    books[j] = books[j + 1];
                    books[j + 1] = temp;
                }

            }
        }
        for (int i = 0; i < books.length; i++) {
            System.out.println(books[i]);
        }
    }
}
class Book{
    private String name;
    private int price;

    @Override
    public String toString() {
        return "Book{" +
                "name='" + name + '\'' +
                ", price=" + price +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public Book(String name, int price) {
        this.name = name;
        this.price = price;
    }
}
